﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using Newtonsoft.Json;
using Power.Common;
using Power.Models;
using Power.View;
using Power.View.Dialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using static Power.ViewModel.AIDistinguishViewModel;

namespace Power.ViewModel
{
    public class AIDistinguishDetailViewModel : ViewModelBase
    {
        private DispatcherTimer timer = new DispatcherTimer();
        private AIDistinguishDetail model;
        public int VideoStatus { get; set; }
        public DefectEntity DefectEntityOld { get; set; }
        public AIDistinguishDetailViewModel(AIDistinguishDetail model)
        {
            this.model = model;
            this.model.Loaded += AITool_Loaded;
            this.model.mediaElement.MediaOpened += mediaElement_MediaOpened;
            this.model.volumeSlider.ValueChanged += volumeSlider_ValueChanged;
            this.model.datagrid.SelectedCellsChanged += datagrid_SelectedCellsChanged;
            this.model.KeyDown += UserControl_KeyDown;
            this.model.datagrid2.SelectedCellsChanged += datagrid2_SelectedCellsChanged;
            ShowAddDefects = new RelayCommand<string>(OnShowAddDefects);
            Start = new RelayCommand(OnStart);
            Pause = new RelayCommand(OnPause);
            Del = new RelayCommand(OnDel);
            Up = new RelayCommand(OnUp);
            Down = new RelayCommand(OnDown);
            Save1 = new RelayCommand(OnSave1);
            Save2 = new RelayCommand(OnSave2);
            DoubleClick = new RelayCommand<DefectEntity>(OnDoubleClick);
            OnStart();
            OnPause();
            #region 数据绑定
            Data = new AIDistinguishDetailData()
            {
                VideoList = new ObservableCollection<VideoEntity>() {
                    new VideoEntity() { Id = "1", Name = "YSJIK53-YSJIK57", Status = 1, StatusDesc = GetStatusDesc(1), Video = $@"\Resources\video\1234.mp4" },
                    new VideoEntity() { Id = "2", Name = "YSJIK53-YSJIK58", Status = 2, StatusDesc = GetStatusDesc(2), Video = $@"\Resources\video\123.mp4" },
                    new VideoEntity() { Id = "3", Name = "YSJIK53-YSJIK59", Status = 3, StatusDesc = GetStatusDesc(3), Video = $@"\Resources\video\1234.mp4" },
                    new VideoEntity() { Id = "4", Name = "YSJIK53-YSJIK59", Status = 3, StatusDesc = GetStatusDesc(3), Video = $@"\Resources\video\123.mp4" },
                    new VideoEntity() { Id = "5", Name = "YSJIK53-YSJIK59", Status = 3, StatusDesc = GetStatusDesc(3), Video = $@"\Resources\video\1234.mp4" },
                    new VideoEntity() { Id = "6", Name = "YSJIK53-YSJIK59", Status = 3, StatusDesc = GetStatusDesc(3), Video = $@"\Resources\video\123.mp4" }
                },
                //下方名称下拉框1
                NameSelectList = Common.Common.GetNameList(),
                //下方类型下拉框2
                TypeSelectList = Common.Common.GetTypeList(),
                //下方等级下拉框3
                LevelSelectList = Common.Common.GetLevelList(),
                DetectEntity = new DetectEntity() { Direction= "SL", Length = 34.24, Date= "2020/04/07", Batch=1, Detector= "张三", Subcontractors= "分包商A" },
                PipEntity = new PipEntity() { Type="YS", Mat="PE", Diameter=10.10, Length=10.10, AreaParam="05", SolidParam="12" },
                StartWellEntity = new WellEntity() { No= "01HL42", Type= "检查井", FuncType= "连接暗井", Mat= "PE", Problem= "井盖破损" },
                EndWellEntity = new WellEntity() { No = "01HL42", Type = "检查井", FuncType = "溢流井", Mat = "PE", Problem = "井内有破损" }
            };
            if (!string.IsNullOrWhiteSpace(this.model.fromID)) {
                //strArr 第一个为工作区域ID，第二个为视频ID
                string[] strArr = this.model.fromID.Split('|');
                //判断视频id不为空，默认选中视频
                if (!string.IsNullOrWhiteSpace(strArr[1]))
                {
                    var item = this.Data.VideoList.FirstOrDefault(a => a.Id == strArr[1]);
                    int index = this.Data.VideoList.IndexOf(item);
                    this.model.datagrid.SelectedIndex = index;
                    this.model.mediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + this.Data.VideoList[index].Video, UriKind.Absolute);
                }
                else {
                    //直接点击复核模式，默认选中第一个视频
                    this.model.datagrid.SelectedIndex = 0;
                    this.model.mediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + this.Data.VideoList[0].Video, UriKind.Absolute);
                }
            }
            #endregion
        }

        /// <summary>
        /// 双击跳转到指定开始时间
        /// </summary>
        /// <param name="obj"></param>
        private void OnDoubleClick(DefectEntity obj)
        {
            this.model.mediaElement.Position = TimeSpan.FromSeconds(obj.StartPos);
        }

        /// <summary>
        /// 右侧保存
        /// </summary>
        private void OnSave2()
        {
            MessagePrompt box = new MessagePrompt("是否保存？",true);
            var flag = box.ShowDialog();
            if (flag == true)
            {
                var detectEntity = this.Data.DetectEntity;
                var pipEntity = this.Data.PipEntity;
                var startWellEntity = this.Data.StartWellEntity;
                var endWellEntity = this.Data.EndWellEntity;
            }
        }

        /// <summary>
        /// 下方保存
        /// </summary>
        private void OnSave1()
        {
            MessagePrompt box = new MessagePrompt("是否保存该条缺陷？", true);
            var flag = box.ShowDialog();
            if (flag == true)
            {
                this.DefectEntityOld = JsonConvert.DeserializeObject<DefectEntity>(JsonConvert.SerializeObject(this.Data.DefectModel));
            }
        }

        /// <summary>
        /// 下一条
        /// </summary>
        private void OnDown()
        {
            if (this.Data.DefectModel.IsChanged(this.DefectEntityOld)) {
                MessagePrompt box = new MessagePrompt("存在未保存的修改，是否将该缺陷状态置为“复核完成”并上传至数据库？", true);
                var flag = box.ShowDialog();
                if (flag == true)
                {
                    this.DefectEntityOld = JsonConvert.DeserializeObject<DefectEntity>(JsonConvert.SerializeObject(this.Data.DefectModel));
                }
            }
            var model = this.Data.DefectModel;
            var index = this.Data.DefectList.IndexOf(model);
            if (index < this.Data.DefectList.Count - 1)
            {
                //设置左侧选中下一条
                this.model.datagrid2.SelectedIndex = index + 1;
            }
        }

        /// <summary>
        /// 上一条
        /// </summary>
        private void OnUp()
        {
            if (this.Data.DefectModel.IsChanged(this.DefectEntityOld))
            {
                MessagePrompt box = new MessagePrompt("存在未保存的修改，是否将该缺陷状态置为“复核完成”并上传至数据库？", true);
                var flag = box.ShowDialog();
                if (flag == true)
                {
                    this.DefectEntityOld = JsonConvert.DeserializeObject<DefectEntity>(JsonConvert.SerializeObject(this.Data.DefectModel));
                }
            }
            var model = this.Data.DefectModel;
            var index = this.Data.DefectList.IndexOf(model);
            if (index > 0)
            {
                //设置左侧选中上一条
                this.model.datagrid2.SelectedIndex = index - 1;
            }
        }

        /// <summary>
        /// 下方删除
        /// </summary>
        private void OnDel()
        {
            MessagePrompt box = new MessagePrompt("是否删除该条缺陷？", true);
            var flag = box.ShowDialog();
            if (flag == true)
            {
                var model = this.Data.DefectModel;
            }
        }

        /// <summary>
        /// 暂停播放
        /// </summary>
        private void OnPause()
        {
            this.model.mediaElement.Pause();
            VideoStatus = -1;
            this.model.btnStart.Visibility = Visibility.Visible;
            this.model.btnPause.Visibility = Visibility.Hidden;
        }

        private string btnStartImage = "/Resources/images/start.png";
        public string BtnStartImage { 
            get {
                return btnStartImage;
            } set {
                btnStartImage = value;
                RaisePropertyChanged();
            } } 
        private void OnFinished()
        {
            this.model.mediaElement.Pause();
            VideoStatus = 0;

            BtnStartImage = "/Resources/images/restart.png";
            this.model.btnStart.Visibility = Visibility.Visible;
            this.model.btnPause.Visibility = Visibility.Hidden;
        }
        /// <summary>
        /// 进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            this.model.time.Content = string.Format("{0:00}:{1:00}:{2:00}",
            this.model.mediaElement.Position.Hours,
            this.model.mediaElement.Position.Minutes,
            this.model.mediaElement.Position.Seconds);


            this.model.volumeSlider.Value = this.model.mediaElement.Position.TotalSeconds;

            if (this.model.mediaElement.Position.TotalSeconds == this.model.volumeSlider.Maximum)
            {
                OnFinished();
            }
        }

        /// <summary>
        /// 计时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AITool_Loaded(object sender, RoutedEventArgs e)
        {
            this.timer.Interval = TimeSpan.FromMilliseconds(50);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        /// <summary>
        /// 开始播放
        /// </summary>
        private void OnStart()
        {
            if (VideoStatus == 0)
                this.model.mediaElement.Position = new TimeSpan(0);

            this.model.mediaElement.Play();
            VideoStatus = 1;
            BtnStartImage = "/Resources/images/start.png";
            this.model.btnStart.Visibility = Visibility.Hidden;
            this.model.btnPause.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 添加缺陷点击
        /// </summary>
        private void OnShowAddDefects(string type)
        {
            if (type == "0")
            {
                OnPause();
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)this.model.mediaElement.ActualWidth,
            (int)this.model.mediaElement.ActualHeight, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(this.model.mediaElement);
                AddDefects box = new AddDefects(bmp, new DefectEntity() {Name="0", Type="0",Level=0 });
                box.ShowDialog();

            }
            else if (type == "1")
            {
                OnPause();
                var image = this.model.defectImage.ImageSource;
                AddDefects box = new AddDefects(image, this.Data.DefectModel);
                box.ShowDialog();
            }
            
            //AddDefects.ShowDialog(System.Windows.Window.GetWindow(this.model));
        }


        private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            model.volumeSlider.Maximum = model.mediaElement.NaturalDuration.TimeSpan.TotalSeconds;
            this.model.mediaElement.Focus();
        }

        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            model.mediaElement.Position = TimeSpan.FromSeconds(model.volumeSlider.Value);
        }

        private void datagrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            VideoEntity entity = (VideoEntity)e.AddedCells[0].Item;
            //此处可以处理视频点击的时候的视频切换
            this.model.mediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + entity.Video, UriKind.Absolute);

            //由于选中事件冲突,初始化缺陷列表防在此处防止重复请求
            if (entity.Id == "1") //演示联动效果，请根据具体需求实现效果
            {
                Data.DefectList = new ObservableCollection<DefectEntity>() {
                        new DefectEntity(){ No = 1,PicName="1",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "1")?.SelectItem ,Name="1",Level=1,StartPos=10,EndPos=20,Type="1",CircleDirection="12",DetectDate="2021/04/07",Describe="描述1",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 2,PicName="2",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "2")?.SelectItem,Name="2",Level=2,StartPos=20,EndPos=30,Type="2",CircleDirection="13",DetectDate="2021/04/08",Describe="描述2",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 3,PicName="3",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 4,PicName="4",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 5,PicName="5",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 6,PicName="6",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 7,PicName="7",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 8,PicName="8",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 9,PicName="9",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 10,PicName="10",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 11,PicName="11",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 12,PicName="12",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 13,PicName="13",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "3")?.SelectItem,Name="3",Level=3,StartPos=30,EndPos=40,Type="3",CircleDirection="14",DetectDate="2021/04/09",Describe="描述3",PicUri="/Resources/images/ais1.png"}
                };
            }
            else
            {
                Data.DefectList = new ObservableCollection<DefectEntity>() {
                        new DefectEntity(){ No = 1,PicName="0",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "0")?.SelectItem ,Name="0",Level=1,StartPos=10,EndPos=20,Type="1",CircleDirection="12",DetectDate="2021/04/07",Describe="描述1",PicUri="/Resources/images/ais1.png"},
                        new DefectEntity(){ No = 2,PicName="1",NameDesc=Common.Common.GetNameList().FirstOrDefault(a=>a.SelectID == "1")?.SelectItem,Name="1",Level=2,StartPos=20,EndPos=30,Type="2",CircleDirection="13",DetectDate="2021/04/08",Describe="描述2",PicUri="/Resources/images/ais1.png"},
                };
            }
            //默认选中第一个缺陷
            this.model.datagrid2.SelectedIndex = 0;
        }

        private void UserControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.KeyStates == Keyboard.GetKeyStates(Key.Left))
            {
                e.Handled = true;
                var postion = this.model.mediaElement.Position - TimeSpan.FromSeconds(1);
                if (postion.TotalSeconds >= 0)
                {
                    this.model.mediaElement.Position = postion;
                }
                else
                {
                    this.model.mediaElement.Position = TimeSpan.FromSeconds(0);
                }
                
            }
            else if (e.KeyStates == Keyboard.GetKeyStates(Key.Right))
            {
                e.Handled = true;
                var postion = this.model.mediaElement.Position + TimeSpan.FromSeconds(1);
                if (postion.TotalSeconds <= model.volumeSlider.Maximum)
                {
                    this.model.mediaElement.Position = postion;

                }
                else
                {
                    this.model.mediaElement.Position = TimeSpan.FromSeconds(model.volumeSlider.Maximum);
                }
            }
        }

        private void datagrid2_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            //设置缺陷详情
            if (e.AddedCells.Count == 0)
            {
                this.Data.DefectModel = Data.DefectList.FirstOrDefault();
            }
            else
            {
                DefectEntity entity = (DefectEntity)e.AddedCells[0].Item;
                this.Data.DefectModel = Data.DefectList.FirstOrDefault(a => a.No == entity.No);
            }
            this.DefectEntityOld = JsonConvert.DeserializeObject<DefectEntity>(JsonConvert.SerializeObject(this.Data.DefectModel));
        }

        #region Command
        public RelayCommand<string> ShowAddDefects { get; private set; }

        public RelayCommand Start { get; private set; }

        public RelayCommand Pause { get; private set; }
        public RelayCommand Del { get; private set; }
        public RelayCommand Up { get; private set; }
        public RelayCommand Down { get; private set; }
        public RelayCommand Save1 { get; private set; }
        public RelayCommand Save2 { get; private set; }
        public RelayCommand<DefectEntity> DoubleClick { get; private set; }
        #endregion

        #region 数据绑定
        public AIDistinguishDetailData Data { get; private set; }

        public class AIDistinguishDetailData : BaseModel
        {
            private ObservableCollection<VideoEntity> videoList;
            public ObservableCollection<VideoEntity> VideoList
            {
                get
                {
                    return videoList;
                }
                set
                {
                    videoList = value;
                    RaisePropertyChanged();
                }
            }

            private ObservableCollection<DefectEntity> defectList;
            public ObservableCollection<DefectEntity> DefectList
            {
                get
                {
                    return defectList;
                }
                set
                {
                    defectList = value;
                    RaisePropertyChanged();
                }
            }
            private DefectEntity defectModel;
            public DefectEntity DefectModel
            {
                get
                {
                    return defectModel;
                }
                set
                {
                    defectModel = value;
                    RaisePropertyChanged();
                }
            }
            private DetectEntity detectEntity;
            public DetectEntity DetectEntity
            {
                get
                {
                    return detectEntity;
                }
                set
                {
                    detectEntity = value;
                    RaisePropertyChanged();
                }
            }

            private PipEntity pipEntity;
            public PipEntity PipEntity
            {
                get
                {
                    return pipEntity;
                }
                set
                {
                    pipEntity = value;
                    RaisePropertyChanged();
                }
            }

            private WellEntity startWellEntity;
            public WellEntity StartWellEntity
            {
                get
                {
                    return startWellEntity;
                }
                set
                {
                    startWellEntity = value;
                    RaisePropertyChanged();
                }
            }

            private WellEntity endWellEntity;
            public WellEntity EndWellEntity
            {
                get
                {
                    return endWellEntity;
                }
                set
                {
                    endWellEntity = value;
                    RaisePropertyChanged();
                }
            }

            private List<SelectListItem> selectList1;
            public List<SelectListItem> NameSelectList
            {
                get => selectList1;
                set
                {
                    selectList1 = value;
                    RaisePropertyChanged();
                }
            }

            private List<SelectListItem> selectList2;
            public List<SelectListItem> TypeSelectList
            {
                get => selectList2;
                set
                {
                    selectList2 = value;
                    RaisePropertyChanged();
                }
            }

            private List<SelectListItem> levelSelectList;
            public List<SelectListItem> LevelSelectList
            {
                get => levelSelectList;
                set
                {
                    levelSelectList = value;
                    RaisePropertyChanged();
                }
            }

            private List<SelectListItem> selectList4;
            public List<SelectListItem> SelectList4
            {
                get => selectList4;
                set
                {
                    selectList4 = value;
                    RaisePropertyChanged();
                }
            }
        }

        #region 数据绑定辅助方法
        private string GetStatusDesc(int status)
        {
            string statusDesc = "";
            switch (status)
            {   case 1:
                    statusDesc = "AI识别";
                    break;
                case 2:
                    statusDesc = "正在检测";
                    break;
                case 3:
                    statusDesc = "待复核";
                    break;
                default:
                    break;
            }
            return statusDesc;
        }
        #endregion
        #endregion
    }
}
